#include "QvernoteMainView.h"
#include <QDeclarativeEngine>
#include <QDeclarativeComponent>
#include <QDeclarativeItem>
#include <QDeclarativeContext>
#include <QDeclarativeProperty>

QvernoteMainView::QvernoteMainView(MApplicationWindow *parent) :
        QvernoteWindow(parent), m_hEvernote(QvernoteAPI::Instance())
{
    m_mainView = new QDeclarativeView(QUrl("qrc:widgets/MainWindow.qml"));
    m_centralWidget = new QGraphicsWidget();

    QGraphicsObject* item = qobject_cast<QGraphicsObject*>(m_mainView->rootObject());
    QObject::connect(item, SIGNAL(allNotesClicked()), this, SLOT(onAllNotesClicked()));
    QObject::connect(item, SIGNAL(notebooksClicked()), this, SLOT(onNotebooksClicked()));

    item->setParentItem(m_centralWidget);

    setCentralWidget(m_centralWidget);
    setTitle("Evernote");

    /* Start syncing the account */
    if(m_hEvernote->isOnline())
    {
        QDeclarativeProperty::write(m_mainView->rootObject(), "statusText", "Syncing notes...");
        QObject::connect(m_hEvernote, SIGNAL(syncProgressUpdated(int,int)), this, SLOT(onUpdateSyncProgress(int, int)));
        QtConcurrent::run(Synchronize, this);
    }
}

QDeclarativeView* QvernoteMainView::GetMainView()
{
    return m_mainView;
}

void QvernoteMainView::onAllNotesClicked()
{

}

void QvernoteMainView::onNotebooksClicked()
{

}

void QvernoteMainView::onUpdateSyncProgress(int cur, int total)
{
    QMetaObject::invokeMethod(m_mainView->rootObject(), "updateSyncProgress",
                              Q_ARG(QVariant, QVariant::fromValue(cur)),
                              Q_ARG(QVariant, QVariant::fromValue(total)));
}

void QvernoteMainView::onOrientationChanged(M::Orientation o)
{
    qDebug() << __FUNCTION__;
    QDeclarativeProperty::write(m_mainView->rootObject(), "inPortrait", (o == M::Portrait)? true : false);
}

void QvernoteMainView::Synchronize(QvernoteMainView* obj)
{
    qDebug() << __FUNCTION__ << "running";
    QvernoteAPI::Instance()->synchronizeLocalStorage();
}
